<?php

namespace app\api\controller;
use think\admin\Controller;
use think\Request;
/**
 * vip会员
 */
class Vip extends Controller
{
    private $default_type = 'json';
    protected $middleware = ['check','auth'];
    public $request;
    public function __construct(Request $request){
        $this->request = $request;
    }

    /**
     * 充会员  获取信息
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getVip(){
        if($this->request->debug != 1) {
            $tokeninfo = $this->request->tokeninfo;
            if (empty($tokeninfo)) {
                return \Tools::returnMsg(false, array(
                    'code' => '100001',
                    'message' => '未登录'
                ), $this->default_type);
            }
            $vipList = json_decode(htmlspecialchars_decode(sysconf('vip_lists_card')),true);
            if(empty($vipList)) $vipList = [];
            return \Tools::returnMsg(true,$vipList,$this->default_type);
        }else{
            return \Tools::returnMsg(true,array(
                array(
                    'type'    => 1,
                    'name'  => '次卡',
                    'amount'=> '150',
                    'remark'=>'年卡有效期为一个自然年，到期不续费不再享有会员权益'
                ),
                array(
                    'type'    => 0,
                    'name'  => '年卡',
                    'amount'=> '150',
                    'remark'=>'年卡有效期为一个自然年，到期不续费不再享有会员权益'
                ),
            ),$this->default_type);
        }
    }

    /**
     * 会员权益
     * @return void
     */
    public function right(){
        $vip_agreement = sysconf('vip_agreement');
        return \Tools::returnMsg(true,$vip_agreement,$this->default_type);
    }
    /**
     * 会员下单
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function placeorder(){
        if($this->request->debug != 1) {
            $tokeninfo = $this->request->tokeninfo;
            if(empty($tokeninfo)) {
                return \Tools::returnMsg(false, array(
                    'code' => '100001',
                    'message' => '未登录'
                ), $this->default_type);
            }
            $vip_type = input('vip_type', 0, 'trim,intval');//年费包类型  0 包年  1 次卡
            if (empty($tokeninfo['openid'])) {
                return \Tools::returnMsg(false, array(
                    'code' => '10008',
                    'message' => '必传参数openid不能为空'
                ), $this->default_type);
            }
            $uid = $tokeninfo['id'];
            $userModel = new \app\api\model\DataUser();
            $uinfo = $userModel->getOne(array(
                'id' => $tokeninfo['id'],
                'status' => 1
            ));
            if (empty($uinfo)) {
                return \Tools::returnMsg(false, array(
                    'code' => '10041',
                    'message' => '学生状态异常'
                ), $this->default_type);
            }
            $orderModel = new \app\api\model\ShopOrder();
            $order = $orderModel->getInfoBytime(array(
                'uuid'          => $uid,
                'status'        => 2,
                'payment_type'  => 2,
                'vip_type'      => $vip_type
            ),'create_at',\Tools::getDateTimeByTime(time() - 3600));
            if (empty($order) === FALSE) {
                $result['msg'] = json_decode($order['payment_remark'], true);
                $result['msg']['expire_at'] = strtotime($order['create_at']) + 7200;
                unset($result['msg']['appId']);
                $rrr = $result['msg'];
                $rrr['total_fee'] = sprintf("%.2f", $order['payment_amount'] / 100);
                $body = sysconf('app_name').'开通VIP会员订单,金额为' . $order['payment_amount'] / 100;
                $rrr['body'] = $body;
                $rrr['merchant'] = sysconf('app_name');
                $rrr['order_no'] = $order['order_no'];
                return \Tools::returnMsg(true, $rrr, $this->default_type);
            }
            $order_no = \Tools::createOrder($uid,2);
            $amount = 0;
            $vipList = json_decode(htmlspecialchars_decode(sysconf('vip_lists_card')),true);
            if(empty($vipList) === FALSE){
                foreach($vipList as &$v){
                    if($v['type'] == $vip_type){
                        $amount = $v['amount'];
                    }
                }
            }
            $body = sysconf('app_name').'开通VIP会员订单,金额为' . $amount / 100;
            $data = array(
                'uuid' => $tokeninfo['id'],
                'order_no' => $order_no,
                'amount_total' => $amount,
                'payment_type' => 2,
                'payment_amount' => $amount,
                'status'=>2,
                'create_at' => \Tools::getDateTimeByTime(),
                'spbill_create_ip' => \Tools::getRemoteAddr(),
                'date' => \Tools::getDateTimeByTime(time(),'Y-m-d'),
                'order_detail' => json_encode(array(
                    'openid'    => $tokeninfo['id'],
                    'vip_type'  => $vip_type
                )),
            );
            $res = $orderModel->addData($data);
            if ($res) {
                $notify_url = $this->request->domain() . '/index/order/vipnotify';      // 微信服务器异步通知
                $spbill_create_ip = \Tools::getRemoteAddr();    // 客户端ip
                $openid = $tokeninfo['openid'];                           // 用户openid
                $total_fee = $amount;                // 支付金额, 单位：分
                $time_start = \Tools::getDateTimeByTime();
                $time_expire = \Tools::getDateTimeByTime(time() + 7200);
                $goods_id = 1;                                      //成为会员，属于支付的商品之一，暂定id为：1
                $trade_type = 'JSAPI';
                $mech_id = sysconf('merchant_no');
                $appid = sysconf('wx_appid');
                $key = sysconf('token');
                // 实例微信支付基类
                $weixinPay = new \Wxinpay($trade_type, $openid, $order_no, $body, $total_fee, $notify_url, $spbill_create_ip, 0, $appid, $mech_id, $key);
                // 发起微信支付
                $result = $weixinPay->pay();
                if ($result['code'] == 0) {      // 统一下单出错
                    $orderModel->saveData(array(
                         'order_no' => $order_no
                    ), array(
                        'status' => 0,
                        'payment_remark' => $result['msg'],
                        'update_at' => \Tools::getDateTimeByTime()
                    ));
                    return \Tools::returnMsg(false, array(
                        'code' => '10041',
                        'message' => '订单生成失败'
                    ));
                }
                // 获取预支付返回参成功
                $prepay_id = $result['msg']['prepay_id'];
                $res = $orderModel->saveData(array(
                    'order_no' => $order_no
                ), array(
                    'payment_trade' => $prepay_id,
                    'payment_remark' => json_encode($result['msg']),
                    'spbill_create_ip' => $spbill_create_ip,
                    'update_at' => \Tools::getDateTimeByTime()
                ));
                if ($res === false) {
                    return \Tools::returnMsg(false, array(
                        'code' => '10041',
                        'message' => '订单生成失败'
                    ));
                }
                $result['msg']['time_expire'] = $time_expire;
                unset($result['msg']['appId']);
                $rrr = $result['msg'];
                $rrr['total_fee'] = sprintf("%.2f", $total_fee / 100);
                $rrr['body'] = $body;
                $rrr['merchant'] = sysconf('app_name');
                $rrr['order_no'] = $order_no;

                return \Tools::returnMsg(true, $rrr, $this->default_type);
            } else {
                return \Tools::returnMsg(false, array(
                    'code' => '10041',
                    'message' => '订单生成失败'
                ), $this->default_type);
            }
        }else{
            return \Tools::returnMsg(true,array(

            ),$this->default_type);
        }
    }
}
